from datetime import datetime
from typing import List, Optional, Dict, Any
from sqlalchemy import Column, String, DateTime, Integer, Text, JSON, ForeignKey, Boolean, BigInteger
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()


class KnowledgeBase(Base):
    """知识库表"""
    __tablename__ = 'knowledge_bases'

    id = Column(String(64), primary_key=True, index=True)
    name = Column(String(255), nullable=False, index=True)
    description = Column(Text, nullable=True)
    status = Column(String(20), default='active', nullable=False)  # active, inactive, building
    # 知识库设置
    settings = Column(JSON, nullable=True, default=lambda: {
        'chunk_size': 1000,
        'chunk_overlap': 200,
        'text_split_strategy': 'fixed_chars',
        'split_chars': ['\n\n', '\n', '。', '！', '？', '；'],
        'index_type': 'vector'
    })
    created_at = Column(DateTime, default=datetime.now, nullable=False)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)

    # 关系
    files = relationship("KnowledgeBaseFile", back_populates="knowledge_base", cascade="all, delete-orphan")


class UploadedFile(Base):
    """已上传文件表"""
    __tablename__ = 'uploaded_files'

    id = Column(String(64), primary_key=True, index=True)
    filename = Column(String(255), nullable=False)
    original_filename = Column(String(255), nullable=False)
    file_path = Column(String(512), nullable=False)
    file_size = Column(BigInteger, nullable=False)
    file_type = Column(String(50), nullable=False)
    mime_type = Column(String(100), nullable=True)
    created_at = Column(DateTime, default=datetime.now, nullable=False)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    is_processed = Column(Boolean, default=False, nullable=False)

    # 关系
    knowledge_base_files = relationship("KnowledgeBaseFile", back_populates="file")


class KnowledgeBaseFile(Base):
    """知识库文件关联表"""
    __tablename__ = 'knowledge_base_files'

    id = Column(String(64), primary_key=True, index=True)
    knowledge_base_id = Column(String(64), ForeignKey('knowledge_bases.id'), nullable=False)
    file_id = Column(String(64), ForeignKey('uploaded_files.id'), nullable=False)
    added_at = Column(DateTime, default=datetime.now, nullable=False)
    status = Column(String(20), default='pending', nullable=False)  # pending, processing, completed, failed

    # 关系
    knowledge_base = relationship("KnowledgeBase", back_populates="files")
    file = relationship("UploadedFile", back_populates="knowledge_base_files")
